var input = document.querySelectorAll('input');
var select = document.querySelector('select');
var textarea = document.querySelector('textarea');
var btn = document.querySelector('.btn');
var sex = document.getElementsByName('sex');
var hobby = document.getElementsByName('hobby');
var i = document.querySelector('i');
var url = "http://localhost:3008";
var getAPI = "/api/student/getStudent";
var addAPI = "/api/student/addStudent";
var updateAPI = "/api/student/updateStudent";
var signId = location.search.split('=')[1];

// 判断是添加还是修改
if (signId) {
    i.innerText = '修改';
    btn.innerText = '修改';
    // 修改时先获取数据
    getData(url + getAPI, { id: signId }, show);

    function show(data) {
        data.forEach(function(value) {
            input[0].value = value.clazz;
            input[1].value = value.name;
            sex.forEach(function(sv) {
                if (sv.value == value.gender) {
                    sv.checked = true;
                }
            })
            input[4].value = value.age;
            hobby.forEach(function(hv) {
                value.hobby.forEach(function(vhv) {
                    if (hv.value == vhv) {
                        hv.checked = true;
                    }
                })
            })
            input[8].value = value.tel;
            select.value = value.address;
            textarea.value = value.remark;
            input[9].value = value.date;
        })
    }
} else {
    i.innerText = '添加';
    btn.innerText = '添加';
}

btn.onclick = function() {
    // 获取性别
    var sexV = null;
    sex.forEach(function(v) {
        if (v.checked) {
            sexV = v.value;
        }
    });
    // 获取爱好
    var hob = [];
    hobby.forEach(function(v) {
        if (v.checked) {
            hob.push(v.value);
        }
    });
    var obj = {
        id: signId,
        clazz: input[0].value,
        name: input[1].value,
        gender: sexV,
        age: input[4].value,
        hobby: hob,
        tel: input[8].value,
        address: select.value,
        remark: textarea.value,
        date: input[9].value,
    }
    if (btn.innerText == '添加') {
        postData(url + addAPI, obj, tips);

        function tips() {
            alert('添加成功');
        }
    } else if (btn.innerText == '修改') {
        postData(url + updateAPI, obj, tips);

        function tips() {
            alert('修改成功');
        }
    }
}